package ue.client.core;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import ue.client.networking.Client;

public class LoginWindow {
	
	public static JFrame loginFrame;
	public static JTextField ipField, portField, nameField;
	public static JPasswordField passwordField;
	public static JButton connectButton;
	
	public LoginWindow() {
		loginFrame = new JFrame("Unto Eternity - Connect");
		loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		loginFrame.setResizable(false);
		
		ipField = new JTextField(10);
		portField = new JTextField(10);
		nameField = new JTextField(10);
		passwordField = new JPasswordField(10);
		
		//DEBUG
		ipField.setText("127.0.0.1");
		portField.setText("7777");
		nameField.setText("asdf");
		passwordField.setText("1234");
		//DEBUG END
		
		connectButton = new JButton("Connect");
		connectButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {				
				Game.client = new Client(ipField.getText(), Integer.parseInt(portField.getText()), 
						nameField.getText(), new String(passwordField.getPassword()));
			}
		});
		
		Box box = new Box(BoxLayout.Y_AXIS);
		Box xBox = new Box(BoxLayout.X_AXIS);
		
		Box[] boxes = generateFieldBoxes(new String[] { "IP", "Port", "Name", "Password" },
										 new JTextField[] { ipField, portField, nameField, passwordField });
		
		xBox.add(boxes[0]);
		xBox.add(boxes[1]);
		box.add(xBox);
		box.add(connectButton);
		
		loginFrame.add(box);
		
		loginFrame.pack();
		
		loginFrame.setVisible(true);
	}
	
	private static Box[] generateFieldBoxes(String[] names, JTextField[] fields) {
		if(names.length != fields.length) return null;
		
		Box[] boxes = new Box[2];
		
		boxes[0] = new Box(BoxLayout.Y_AXIS);
		boxes[1] = new Box(BoxLayout.Y_AXIS);
		
		for(int i = 0; i < names.length; i++) {
			boxes[0].add(new JLabel(names[i] + ": "));
			boxes[1].add(fields[i]);
		}
		
		return boxes;
	}
	
	public void dispose() {
		loginFrame.dispose();
	}
}
